import fs from "fs-extra";
import path from "path";
import { TaskResult } from "../../common/tasks/BastTask.js";
import { toolchain } from "../../toolchain.js";
import { WebGLEnv } from "../WebGLEnv.js";
import { BuildUnityResult, WebGLBuildUnityBaseTask } from './WebGLBuildUnityBaseTask.js';
import { replaceInFileOrThrow } from "../../tools/vendor.js";

export class WebGLBuildDouyinTask extends WebGLBuildUnityBaseTask {
    async run(): Promise<TaskResult<BuildUnityResult>> {
        const channelCfg = toolchain.params.channelCfg;
        // 修改appid
        const cfgFile = path.join(toolchain.params.workSpacePath, 'Assets/Editor/StarkBuilderSetting.asset');
        replaceInFileOrThrow(cfgFile, /(?<=_appId: )\S+/, channelCfg.douyin!.appid);

        // 调用抖音sdk命令
        const result = await this.callUnity(WebGLEnv.ExportDouyinRoot, 'BuildForDouyin');
        if (!result.success) return result;

        const projectConfigFile = path.join(toolchain.params.workSpacePath, 'project.config.json');
        const configJson: { appid: string, projectname: string } = await fs.readJson(projectConfigFile);
        configJson.appid = channelCfg.douyin!.appid;
        configJson.projectname = channelCfg.productName;
        await fs.writeJson(projectConfigFile, configJson, { spaces: 4 });

        // 写入appVer.txt记录application版本，以供手动上传时使用
        const appVerFile = path.join(toolchain.params.workSpacePath, WebGLEnv.DouyinAppVerFile);
        await fs.writeFile(appVerFile, result.data!.version, 'utf-8');

        return result;
    }
}
